﻿
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;

using FreeSql;
using Kalman;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;

namespace QuDao
{
    /// <summary>
    /// 数据表base_album关联的业务对象，处理该表相关的业务逻辑
    /// </summary>
    public sealed partial class AlbumBO : SingletonBase<AlbumBO>
    {
        readonly IFreeSql fsql;
        public AlbumBO() : base()
        {
            fsql = ServiceLocator.Instance.GetRequiredService<IFreeSql>();
        }

        /// <summary>
        /// 获取相册
        /// </summary>
        /// <param name="id">主键ID的值</param>
        /// <returns></returns>
        public T GetItem<T>(int id)
        {
            if (id <= 0) return default;
            var item = fsql.Select<Album>().Where(a => a.ID == id).ToOne<T>();
            return item;
        }

        public Album GetItem(int id)
        {
            return GetItem<Album>(id);
        }

        /// <summary>
        /// 获取相册数据列表
        /// </summary>
        /// <param name="pageIndex">页索引，从1开始</param>
        /// <param name="pageSize">每页记录数，默认10</param>
        /// <returns></returns>
        public List<AlbumDto> GetListByGoods(int goodsID)
        {
            var list = fsql.Select<Album>()
                .Where(a => a.GoodsID == goodsID)
                .OrderByDescending(a => a.SortFlag)
                .OrderByDescending(a => a.ID)
                .ToList<AlbumDto>();
            return list;
        }

        /// <summary>
        /// 获取相册数据列表
        /// </summary>
        /// <returns></returns>
        public List<T> GetList<T>(int[] ids)
        {
            if (ids == null || ids.Length == 0) return new List<T>();
            var list = fsql.Select<Album>().Where(a => ids.Contains(a.ID)).ToList<T>();
            return list;
        }

        /// <summary>
        /// 新增相册
        /// </summary>
        public int Add(AlbumAddDto dto)
        {
            var goods = GoodsBO.Instance.GetItem(dto.GoodsID);

            var entity = new Album
            {
                TID = goods.TID,
                GoodsID = goods.GoodsID,
                ImageUrl = dto.ImageUrl,
                Width = dto.Width,
                Height = dto.Height,
                FileSize = dto.FileSize,
                SortFlag = dto.SortFlag,
                CreateTime = DateTime.Now,
                ModifyTime = DateTime.Now,
                Memo = dto.Memo
            };

            entity.ID = (int)fsql.Insert(entity).ExecuteIdentity();
            return entity.ID;
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="dtoList"></param>
        /// <returns></returns>
        public int BatchAdd(List<AlbumAddDto> dtoList)
        {
            if (dtoList.Count == 0) return 0;

            var goods = GoodsBO.Instance.GetItem(dtoList[0].GoodsID);
            var list = new List<Album>();
            foreach (var dto in dtoList)
            {
                list.Add(new Album
                {
                    TID = goods.TID,
                    GoodsID = goods.GoodsID,
                    ImageUrl = dto.ImageUrl,
                    Width = dto.Width,
                    Height = dto.Height,
                    FileSize= dto.FileSize,
                    SortFlag = dto.SortFlag,
                    CreateTime = DateTime.Now,
                    ModifyTime = DateTime.Now,
                    Memo = dto.Memo
                });
            }

            return fsql.Insert(list).ExecuteAffrows();
        }

        /// <summary>
        /// 修改相册
        /// </summary>
        public int Modify(AlbumModifyDto dto)
        {
            var item = GetItem<Album>(dto.ID);
            if (item == null) throw new AppException($"相册不存在：{dto.ID}");

            var update = fsql.Update<Album>(dto.ID).Set(a => a.ModifyTime, DateTime.Now);
            if (dto.SortFlag != item.SortFlag) update.Set(a => a.SortFlag, dto.SortFlag);
            if (dto.Memo != item.Memo) update.Set(a => a.Memo, dto.Memo);

            if (!string.IsNullOrEmpty(dto.ImageUrl) && dto.ImageUrl != item.ImageUrl)
            {
                update.Set(a => a.ImageUrl, dto.ImageUrl).Set(a => a.FileSize, dto.FileSize).Set(a => a.Width, dto.Width).Set(a => a.Height, dto.Height);
            }

            return update.ExecuteAffrows();
        }

        /// <summary>
        /// 修改相册（根据字典数据修改）
        /// </summary>
        /// <param name="id">相册ID</param>
        /// <param name="dic">待修改的字典数据（KEY：字段名，Value：修改值）</param>
        public int ModifyByDic(int id, Dictionary<string, object> dic)
        {
            var item = GetItem<Album>(id);
            if (item == null) throw new AppException($"相册不存在：{id}");
            if (dic == null || dic.Count == 0) throw new AppException("字典数据不能为空");

            var update = fsql.Update<Album>(id).Set(a => a.ModifyTime, DateTime.Now);
            //if (dic.ContainsKey("TID")) update.Set(a => a.TID, dic["TID"]);
            if (dic.ContainsKey("SortFlag")) update.Set(a => a.SortFlag, dic["SortFlag"]);
            if (dic.ContainsKey("Memo")) update.Set(a => a.Memo, dic["Memo"]);

            return update.ExecuteAffrows();
        }

        /// <summary>
        /// 修改相册（修改指定字段值）
        /// </summary>
        /// <param name="id">相册ID</param>
        /// <param name="fieldName">字段名</param>
        /// <param name="fieldValue">字段值</param>
        /// <returns></returns>
        public int ModifyByField(int id, string fieldName, object fieldValue)
        {
            var dic = new Dictionary<string, object>
            {
                { fieldName, fieldValue }
            };
            return ModifyByDic(id, dic);
        }

        /// <summary>
        /// 删除相册数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;
            return fsql.Delete<Album>().Where(a => ids.Contains(a.ID)).ExecuteAffrows();
        }

        /// <summary>
        /// 删除相册数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int id)
        {
            var ids = new int[] { id };
            return Delete(ids);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="req">分页查询请求对象</param>
        public PagingResult<T> Query<T>(PagingRequest req, int tid, int goodsID)
        {
            if (req == null) throw new AppException("查询数据不能为空");

            var select = fsql.Select<Album>()
                .Where(a => a.TID == tid)
                .WhereIf(goodsID > 0, a => a.GoodsID == goodsID);
            foreach (var item in req.FilterItems)
            {
                switch (item.Field)
                {
                    //case "RelationID":
                    //    select.Where(a => a.RelationID == long.Parse(item.Value));
                    //    break;
                    //case "AlbumType":
                    //    select.Where(a => a.AlbumType == int.Parse(item.Value));
                    //    break;
                    //case "Title":
                    //    select.Where(a => a.Title.Contains(item.Value));
                    //    break;
                    default:
                        break;
                }
            }

            //select.OrderByDescending(a => a.ID);//默认排序
            select.OrderByDescending(a => a.SortFlag);//默认排序

            var sql = select.ToSql();

            var list = select.Count(out var total).Page(req.PageIndex, req.PageSize).ToList<T>();
            return new PagingResult<T>
            {
                PageIndex = req.PageIndex,
                PageSize = req.PageSize,
                Data = list,
                Total = (int)total
            };
        }

        public PagingResult<Album> Query(PagingRequest req, int tid, int goodsID)
        {
            return Query<Album>(req, tid, goodsID);
        }

    }
}
